/**
 * 封装
 * 网络请求：axios */
import axios from 'axios'
import { Message } from 'element-ui'
import { errorCode } from './errorCode'
import cache from '@/plugins/cache'
import store from '../store/index'
import router from '../router/index'
import { getToken } from '@/utils/cookie'

// import qs from 'qs'
// 处理异常错误
const errorHandle = (status, info) => {
  errorCode(status, info)
}

// 创建axios实例对象
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
})

// 处理并发请求方法
instance.all = axios.all
instance.spread = axios.spread

// 全局配置
instance.defaults.headers.post['Content-Type'] = 'application/json'
instance.defaults.headers.put['Content-Type'] = 'application/json'
instance.defaults.headers.delete['Content-Type'] = 'application/json'

// 请求拦截
instance.interceptors.request.use(
  (config) => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    // 是否需要防止数据重复提交
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false

    if (getToken() && !isToken) {
      config.headers['Authorization-Token'] = getToken() // 让每个请求携带
    }

    config.data = JSON.stringify(config.data)
    if (
      !isRepeatSubmit &&
      (config.method === 'post' || config.method === 'put')
    ) {
      const requestObj = {
        url: config.url,
        data: config.data,
        time: new Date().getTime(),
      }
      const sessionObj = cache.session.getJSON('sessionObj')
      if (
        sessionObj === undefined ||
        sessionObj === null ||
        sessionObj === ''
      ) {
        cache.session.setJSON('sessionObj', requestObj)
      } else {
        const s_url = sessionObj.url // 请求地址
        const s_data = sessionObj.data // 请求数据
        const s_time = sessionObj.time // 请求时间
        const interval = 1000 // 间隔时间(ms)，小于此时间视为重复提交
        if (
          s_data === requestObj.data &&
          requestObj.time - s_time < interval &&
          s_url === requestObj.url
        ) {
          const message = '数据正在处理，请勿重复提交'
          console.warn(`[${s_url}]: ` + message)
          Message({ message: message, type: 'warning' })
          return Promise.reject(new Error(message))
        } else {
          cache.session.setJSON('sessionObj', requestObj)
        }
      }
    }

    return config
  },
  (error) => Promise.reject(error),
)

// 响应拦截
instance.interceptors.response.use(
  // 成功
  (response) => {
    const code = response.data.code
    const msg = response.data.msg
    if (code === 200) {
      return response.data
      // return response
    } else {
      Message({ message: msg, type: 'warning' })
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('error')
    }
  },

  (error) => {
    const { response } = error
    if (response) {
      if (response.status === 401) {
        if (getToken()) {
          console.log('存在无效token')
        }
        store.dispatch('CLEARTOKEN', null).then((res) => {
          console.log(res, '清除成功')
          Message({ message: '账号过期，请重新登录！', type: 'warning' })
          router.push({
            path: '/login/LT',
          })
        })
      }
      /**
       * 错误信息以状态码为主反
       */
      errorHandle(response.status, response.data)
      return Promise.reject(response)
    } else {
      console.log('请求被中断')
    }
  },
)

/**
 * 提供get和post的请求方式
 */
export function get(url, params) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params,
      })
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}
export function post(url, params) {
  return new Promise((resolve, reject) => {
    instance
      .post(url, params)
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
export default instance
